package com.project.homework4_9.dao.impl;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class BaseDao {
    protected Connection con;
    protected PreparedStatement ps;
    protected ResultSet rs;

    /**
     * 创建连接
     */
    public void getConnection() {
        try {
            //加载驱动
            Class.forName("com.mysql.jdbc.Driver");
            //建立连接
            con = DriverManager.getConnection(
                    "jdbc:mysql://localhost:12345/user?characterEncoding=utf-8",
                    "root", "lovo");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void colseConnection(){
        try {
            if (rs != null){
                rs.close();
            }
            if (ps != null){
                ps.close();
            }
            if (con != null){
                con.close();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

//    /**
//     * 建立连接
//     *
//     * @param con 连接对象
//     */
//    public void setConnection(Connection con) {
//        this.con = con;
//    }

    public void updateData(String sql, Object... valueArray) {
        this.getConnection();
        try {
            ps = con.prepareStatement(sql);
            //设置占位符
            for (int i = 0; i < valueArray.length; i++) {
                ps.setObject(i + 1, valueArray[i]);
            }

            ps.executeUpdate();

        } catch (Exception e) {
            e.printStackTrace();
        }
        finally {
            this.colseConnection();
        }
    }
}

